from flask import Blueprint, jsonify
from app.models.building import Building  # 假设存在建筑模型

# 创建建筑相关路由蓝图，前缀为/api
building_bp = Blueprint('building', __name__, url_prefix='/api')

@building_bp.get('/building/recommended')
def get_recommended_buildings():
    """获取推荐建筑列表"""
    try:
        # 从数据库查询推荐的建筑（假设建筑表有is_recommended字段标记推荐状态）
        # 取前6条推荐建筑，按创建时间倒序
        recommended_buildings = Building.collection.find(
            {"is_recommended": True}  # 筛选推荐建筑
        ).sort("created_at", -1).limit(6)

        # 转换为列表并处理ObjectId
        result = []
        for building in recommended_buildings:
            # 将MongoDB的ObjectId转换为字符串
            building["_id"] = str(building["_id"])
            result.append(building)

        return jsonify({
            "code": 0,
            "msg": "获取成功",
            "data": result
        })

    except Exception as e:
        print(f"获取推荐建筑失败: {str(e)}")
        return jsonify({
            "code": -1,
            "msg": f"服务器错误: {str(e)}"
        }), 500